package com.striker.imwebsocket;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.db.dao.KefuConversationMapper;
import org.linlinjava.litemall.db.dao.KefuMessageMapper;
import org.linlinjava.litemall.db.domain.KefuConversation;
import org.linlinjava.litemall.db.domain.KefuConversationExample;
import org.linlinjava.litemall.db.domain.KefuMessage;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class WebSocketService {

    @Resource
    KefuMessageMapper messageMapper;

    @Resource
    KefuConversationMapper conversationMapper;

    @Resource
    LitemallUserService litemallUserService;

    public void insertMsg(KefuMessage msg){
        log.info("客服msg|入db|"+msg);
        messageMapper.insertSelective(msg);
    }

    public void updateConversation(KefuConversation record){
        log.info("会话|入db|"+record);
        KefuConversationExample e = new KefuConversationExample();
        e.or().andUseridEqualTo(record.getUserid());

        LitemallUser user = litemallUserService.findById(record.getUserid());
        if(user != null && user.getUsername() != null) {
            record.setUsername(user.getUsername());
        }
        if(user != null && user.getMobile() != null) {
            record.setMobile(user.getMobile());
        }

        List<KefuConversation> l = conversationMapper.selectByExample(e);
        if(l == null || l.size() == 0){//无就插入
            conversationMapper.insertSelective(record);
        }else {
            conversationMapper.updateByExampleSelective(record, e);
        }
    }
}
